package com.zk.babala.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.zk.babala.BabalaApp;
import com.zk.babala.entity.Movie;
import com.zk.babala.vo.ChannelVO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

/**
 * 播放历史
 */
public class HistoryUtil {
    private final SharedPreferences preferences;
    private final SharedPreferences.Editor editor;
    private static final String preferenceName = "HistoryListTag";
    private static final String movieHistoryListTag = "MovieHistoryList";
    private static final String liveHistoryTag = "LiveHistory";
    private static final String startToLiveHistoryTag = "StartToLiveHistoryTag";
    private static final String bootToApp = "BootToApp";

    private static final String searchHistoryTag = "SearchHistory";
    public HistoryUtil(Context context, String preferenceName) {
        preferences = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    public static HistoryUtil getHistoryInstance() {
        return new HistoryUtil(BabalaApp.getContext(), HistoryUtil.preferenceName);
    }


    public void saveDataJson(String dataJson) {
        if (StrUtil.isNotBlank(dataJson)) {
            editor.putString(HistoryUtil.movieHistoryListTag, dataJson);
            editor.commit();
        }

    }

    /**
     * 保存List
     */
    public void saveDataList(List<Movie> dataList) {
        String dataStr = getHistoryJson();
        Map<String, List<Movie>> map;
        if (dataStr == null) {
            map = new HashMap();
        } else {
            map = JSONUtil.toBean(dataStr, new TypeReference<Map<String, List<Movie>>>() {
            }.getType(), true);
        }
        map.put(LineUtil.getLineUtil().getLineSource(), ListUtil.reverse(dataList));
        dataStr = JSONUtil.toJsonStr(map);
        editor.putString(HistoryUtil.movieHistoryListTag, dataStr);
        editor.commit();

    }

    public String getHistoryJson() {
        return preferences.getString(HistoryUtil.movieHistoryListTag, null);
    }

    /**
     * 获取List
     */
    public List<Movie> getHistoryList() {
        String dataStr = preferences.getString(HistoryUtil.movieHistoryListTag, null);
        try {
            if (dataStr != null) {
                Map<String, List<Movie>> map = JSONUtil.toBean(dataStr, new TypeReference<Map<String, List<Movie>>>() {
                }.getType(), true);
                List<Movie> list = map.get(LineUtil.getLineUtil().getLineSource());
                if (list != null) {
                    return list;
                }
            }
        } catch (Exception e) {
            Toast.makeText(BabalaApp.getContext(), "读取历史记录异常" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        return new ArrayList<>();

    }

    public void addMovieHis(Movie movie) {
        List<Movie> list = getHistoryList();
        list.removeIf(m -> m.getTitle().equals(movie.getTitle()));
        list.add(movie);
        if (list.size() > 30) {
            list.remove(list.size() - 1);
        }
        saveDataList(list);
    }

    public Movie getPlayHis(Movie movie) {
        List<Movie> list = getHistoryList();
        for (int i = 0; i < list.size(); i++) {
            Movie hisMovie = list.get(i);
            if (hisMovie.getTitle().equals(movie.getTitle())) {
                if (hisMovie.getPlayHis() != null) {
                    return hisMovie;
                }
                break;
            }
        }
        return null;
    }

    public void delPlayHis(Movie movie) {
        List<Movie> list = getHistoryList();
        list.removeIf(m -> m.getTitle().equals(movie.getTitle()));
        saveDataList(list);
    }

    public void clearAll() {
        saveDataList(new ArrayList<>());
    }

    public void saveLiveHis(ChannelVO channelVO) {
        editor.putString(liveHistoryTag, JSONUtil.toJsonStr(channelVO));
        editor.commit();
    }

    public ChannelVO getLiveHis() {
        String channelStr = preferences.getString(liveHistoryTag, null);
        if (channelStr == null) {
            return null;
        }
        try {
            return JSONUtil.toBean(channelStr, ChannelVO.class);
        } catch (Exception e) {
            editor.remove(liveHistoryTag);
            editor.commit();
            return null;
        }

    }

    public void saveStartToLive(Boolean live) {
        editor.putBoolean(startToLiveHistoryTag, live);
        editor.commit();
    }

    public Boolean getStartToLive() {
        return preferences.getBoolean(startToLiveHistoryTag, false);
    }

    // 保存开机启动APP设置
    public void saveBootToApp(boolean bootToApp) {
        editor.putBoolean(HistoryUtil.bootToApp, bootToApp);
        editor.commit();
    }

    // 获取开机启动APP设置
    public boolean getBootToApp() {
        return preferences.getBoolean(bootToApp, false);
    }


    /**
     * 保存搜索历史
     *
     * @param searchKey 搜索关键词
     */
    public void saveSearchHistory(String searchKey) {
        if (StrUtil.isBlank(searchKey)) {
            return;
        }

        List<String> searchHistoryList = getSearchHistory();
        // 移除重复的搜索记录
        searchHistoryList.removeIf(s -> s.equals(searchKey));
        // 添加到最前面
        searchHistoryList.add(0, searchKey);

        // 限制历史记录数量为20条
        if (searchHistoryList.size() > 20) {
            searchHistoryList = searchHistoryList.subList(0, 20);
        }

        editor.putString(searchHistoryTag, JSONUtil.toJsonStr(searchHistoryList));
        editor.commit();
    }

    /**
     * 获取搜索历史
     *
     * @return 搜索历史列表
     */
    public List<String> getSearchHistory() {
        String historyStr = preferences.getString(searchHistoryTag, null);
        if (historyStr != null) {
            try {
                return JSONUtil.toList(historyStr, String.class);
            } catch (Exception e) {
                // 如果解析失败，清除错误数据
                editor.remove(searchHistoryTag);
                editor.commit();
            }
        }
        return new ArrayList<>();
    }

    /**
     * 清除搜索历史
     */
    public void clearSearchHistory() {
        editor.remove(searchHistoryTag);
        editor.commit();
    }
}
